package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"html/template"
	"web-docker/common"
	"web-docker/models"
)

type LoginController struct {
	beego.Controller
}


func (c *LoginController) Get() {
	c.Data["title"] = "登录"
	c.Data["_token"] = template.HTML(c.XSRFFormHTML())
	c.TplName = "login/index.tpl"
}

func (c *LoginController) Post()  {
	account := c.Input().Get("account")
	password := c.Input().Get("password")
	if err:= isField(account,password) ;len(err) > 0 {
		c.Data["json"] = common.ResponseJson{Code:401,Message:err,Data:nil}
		c.ServeJSON()
	}
	u := models.Users{Account:account}
	err := u.ReadUser()
	if err == orm.ErrNoRows {
		c.Data["json"] = common.ResponseJson{Code:401,Message:"用户不存在",Data:nil}
		c.ServeJSON()
	}
	c.Data["json"] = common.ResponseJson{Code:200,Message:"测试",Data:nil}
	c.ServeJSON()
}

func isField(account,passwd string)(string){
	var errMsg string
	vaild := validation.Validation{}
	vaild.Required(account,"account")
	vaild.Required(passwd,"password")
	if vaild.HasErrors() {
		for _,err := range vaild.Errors{
			errMsg += err.Message
		}
		return errMsg
	}
	return errMsg
}